package com.tubeonfire.controller.admin;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.logging.Logger;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.tubeonfire.entity.Author;
import com.tubeonfire.entity.Channel;
import com.tubeonfire.entity.Mission;
import com.tubeonfire.entity.Tube;
import com.tubeonfire.model.admin.AuthorModel;
import com.tubeonfire.model.admin.ChannelModel;
import com.tubeonfire.model.admin.MissionModel;
import com.tubeonfire.model.admin.TubeModel;
import com.tubeonfire.service.YoutubeService;
import com.tubeonfire.util.IdUniqueHelper;
import com.tubeonfire.util.TagHelper;

@SuppressWarnings("serial")
public class TaskQueueAdminServlet extends HttpServlet {

	private static final Logger log = Logger
			.getLogger(TaskQueueAdminServlet.class.getName());

	public void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws IOException {
		try {
			String action = req.getParameter("action");
			if (action != null && action.equals("add-all-from-channel")) {
				String channelId = (String) req.getParameter("channelId");
				String playlistId = (String) req.getParameter("playlistId");
				String subcribe = (String) req.getParameter("subcribe");
				try {
					int limit = 49;
					YoutubeService tubeService = new YoutubeService();
					tubeService.setPage(1);
					tubeService.setLimit(limit);
					List<Tube> listToAdd = new ArrayList<Tube>();
					tubeService.searchByChannel(channelId, true);
					for (Tube tube : tubeService.getListResult()) {
						tube = processTubeDetail(playlistId, tube);
						String uri = tube.getAuthorUrl();
						if (uri != null && uri.length() > 0) {
							if (AuthorModel.getById(uri) == null) {
								processAuthor(uri);
							}
						}
						listToAdd.add(tube);
					}
					TubeModel.insert(listToAdd);
					Mission mission = new Mission();
					mission.setId(IdUniqueHelper.getId());
					mission.setSearchHd(1);
					mission.setSearchType(1);
					mission.setSearchKeyword(channelId);
					mission.setPlaylistId(playlistId);
					mission.setSearchLimit(limit);
					if (tubeService.getListResult().size() > 0
							&& !tubeService.isTooManyRecentCallError()) {
						mission.setSearchPage(tubeService.getPage() + 1);
					} else {
						mission.setSearchPage(tubeService.getPage());
					}
					mission.setSearchTotalPage(tubeService.getTotalPage());
					mission.setType(2);
					mission.setTitle("Get all videos from channel " + channelId);
					if (tubeService.getPage() == tubeService.getTotalPage()
							&& !tubeService.isTooManyRecentCallError()) {
						mission.setStatus(2);
					}
					MissionModel.insert(mission);
					if (subcribe != null && subcribe.equals("true")) {
						mission = new Mission();
						mission.setId(IdUniqueHelper.getId());
						mission.setType(1);
						mission.setPlaylistId(playlistId);
						mission.setSearchKeyword(channelId);
						mission.setTitle("Subcribe from channel " + channelId);
						MissionModel.insert(mission);
					}
				} catch (Exception e) {
					log.warning(e.toString());
					e.printStackTrace();
				}
			} else if (action != null && action.equals("add-author")) {
				String uri = (String) req.getParameter("uri");
				if (uri != null && uri.length() > 0) {
					if (AuthorModel.getById(uri) == null) {
						processAuthor(uri);
					}
				}
			}
		} catch (Exception e) {
			log.warning(e.toString());
			e.printStackTrace();
		}
	}

	private void processAuthor(String uri) {
		Author author = new Author();
		author.setUri(uri);
		String[] spl = uri.split("/");
		author.setName(spl[spl.length - 1]);
		author = YoutubeService.getUserProfile(author);
		author.setStatus(1);
		author.setBumpPoint(Calendar.getInstance().getTimeInMillis() / 1000);
		author.setUpdated(Calendar.getInstance().getTime());
		AuthorModel.insert(author);
		com.tubeonfire.model.AuthorModel.clearModelCache();
	}

	private Tube processTubeDetail(String plId, Tube tube) {
		tube.setPlaylistId(plId);
		if (tube.getTags().size() == 0) {
			tube.setTags(TagHelper.youTag(tube.getTitle() + " "
					+ tube.getDescription()));
		}
		tube.setOtherTags(TagHelper.getOtherTag(tube.getTags()));
		tube.setBumpPoint(Calendar.getInstance().getTimeInMillis() / 1000);
		if (ChannelModel.getById(tube.getChannelId()) == null) {
			Channel channel = new Channel();
			channel.setId(tube.getChannelId());
			channel.setTitle(tube.getChannelName());
			channel.setDescription(tube.getChannelName());
			channel.setDoc(Calendar.getInstance().getTime());
			channel.setUpdated(Calendar.getInstance().getTime());
			channel.setBumpPoint(Calendar.getInstance().getTimeInMillis() / 1000);
			channel.setStatus(1);
			ChannelModel.insert(channel);
		}
		return tube;
	}
}
